package com.lwei.ljpro.filter;

import com.lwei.ljpro.emun.CookieName;
import com.lwei.ljpro.entry.UserEntry;
import com.lwei.ljpro.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 访问用户记录拦截器
 */
@Component
@Order(1)
@WebFilter(urlPatterns = {"/*"},filterName = "customerRecordFilter")
public class CustomerRecordFilter implements Filter {

    private Logger logger = LoggerFactory.getLogger("CustomerRecordFilter");
    @Autowired
    private IUserService userService;

    @Override
    public void init(FilterConfig filterConfig) {
        logger.info("用户访问拦截器启动成功");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        Cookie[] cookies = request.getCookies();
        HttpSession session = request.getSession();
        if(session.getAttribute(CookieName.USER_CURRENT.getValue()) != null || request.getRequestURI().contains("login")
                ||request.getRequestURI().contains("static")){
            filterChain.doFilter(request, response);
            return;
        }
        if(cookies != null){
            for (Cookie cookieTel : cookies) {
                // 筛选是否携带电话号码
                if (CookieName.USER_TEL.getValue().equals(cookieTel.getName())) {
                    //验证是否携带用户名
                    for (Cookie cookieUserName : cookies) {
                        if (CookieName.USER_NAME.getValue().equals(cookieUserName.getName())) {
                            Long userId;
                            //老用户查询系统是否有记录，
                            UserEntry user = userService.checkUserByTel(cookieTel.getValue());
                            if (user == null) {
                                //无记录 新增
                                userId = userService.saveUser(new UserEntry(cookieTel.getValue(), cookieUserName.getValue()));
                                user = userService.getEntryById(userId);
                            } else{
                                userId = user.getId();
                            }
                            userService.updateUserLastAliveTime(userId);

                            //验证成功之后验证将cookie转换为session
                            Object userEntry = session.getAttribute(CookieName.USER_CURRENT.getValue());
                            if(userEntry == null){
                                session.setAttribute(CookieName.USER_CURRENT.getValue(), user);
                            }

                            filterChain.doFilter(request, response);
                            return;
                        }
                    }
                    //仅未携带用户名
                    request.setAttribute("userTel", cookieTel.getValue());
                    request.getRequestDispatcher("/login").forward(request, response);
                    return;
                }
            }
            response.sendRedirect("/login");
        }else{
            //新用户跳转创建页面
            response.sendRedirect("/login");
        }
    }

    @Override
    public void destroy() {

    }
}
